<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" clearable style="width: 100px">
            <el-option
              v-for="item in GoodsOrderStatus"
              :key="item"
              :label="GoodsOrderStatus_LABEL[item]"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar"></div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableDatas"
        highlight-current-row
        border
        class="data-table__content"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="订单号" prop="orderNo" width="150" />
        <el-table-column label="客户名称" prop="customerName" width="150" />
        <el-table-column label="状态" align="center" width="80" prop="status">
          <template #default="scope">
            {{ GoodsOrderStatus_LABEL[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" width="80" prop="paymentType" />
        <el-table-column label="总金额" align="center" width="80" prop="totalPrice" />
        <el-table-column label="创建时间" prop="createTime" width="150" />
        <el-table-column label="收件人" align="center" width="80" prop="deliveryName" />
        <el-table-column label="收件电话" align="center" width="150" prop="deliveryPhone" />
        <el-table-column label="收件地址" align="center" min-width="150" prop="deliveryAddress" />
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" link icon="search" @click="gotoPage(scope.row.id)">
              详情
            </el-button>
            <el-button
              type="primary"
              v-if="scope.row.status === GoodsOrderStatus.WAIT_DELIVERY"
              link
              icon="edit"
              @click="showDeliveryDialog(scope.row.id)"
            >
              发货出库
            </el-button>
            <el-button
              type="primary"
              v-if="
                scope.row.status === GoodsOrderStatus.WAIT_DELIVERY ||
                scope.row.status === GoodsOrderStatus.WAIT_PAY
              "
              link
              icon="edit"
              @click="cancel(scope.row.id)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 物理表单弹窗 -->
    <el-dialog
      v-model="deliveryDialog.visible"
      :title="deliveryDialog.title"
      width="600px"
      @close="closeDeliveryDialog"
    >
      <el-form
        ref="devliveryFormRef"
        :model="deliveryForm"
        :rules="deliveryRules"
        label-width="100px"
      >
        <el-form-item label="物流单号" prop="name">
          <el-input v-model="deliveryForm.deliveryNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDelivery">确 定</el-button>
          <el-button @click="closeDeliveryDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useAppStore } from "@/store/modules/app.store";
import router from "@/router";

import type { ElTable } from "element-plus";
const dataTableRef = ref<InstanceType<typeof ElTable>>();
import GoodsOrderAPI, {
  GoodsOrderPageQuery,
  GoodsOrderPageVO,
  GoodsOrderStatus_LABEL,
  GoodsOrderStatus,
  DeliveryInfo,
} from "@/api/goods/goodsOrder.api";

defineOptions({
  name: "GoodsOrder",
  inheritAttrs: false,
});
const devliveryFormRef = ref();
const queryFormRef = ref();

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<GoodsOrderPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 物流表单
const deliveryForm = reactive<DeliveryInfo>({});

// 客户表格数据
const tableDatas = ref<GoodsOrderPageVO[]>();

// 弹窗
const deliveryDialog = reactive({
  title: "填报物流单号-会自动主库并解锁材料的锁定",
  visible: false,
});

function gotoPage(orderId?: string) {
  router.push({
    path: "/goods/orderDetail",
    query: { orderId: orderId, title: "订单详情" },
  });
}

function showDeliveryDialog(orderId?: string) {
  deliveryDialog.visible = true;
  deliveryForm.orderId = orderId;
}

function closeDeliveryDialog() {
  deliveryDialog.visible = false;
  deliveryForm.deliveryNo = "";
  deliveryForm.orderId = "";
}

function submitDelivery() {
  devliveryFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      GoodsOrderAPI.delivery(deliveryForm)
        .then(() => {
          ElMessage.success("操作成功");
          closeDeliveryDialog();
          handleQuery();
        })
        .catch(() => {})
        .finally(() => (loading.value = false));
    }
  });
}

/**
 * 取消订单
 */
function cancel(orderId: string) {
  GoodsOrderAPI.cancel(orderId)
    .then(() => {
      handleQuery();
    })
    .catch(() => {});
}

// 获取数据
function fetchData() {
  loading.value = true;
  GoodsOrderAPI.getPage(queryParams)
    .then((data) => {
      tableDatas.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

const deliveryRules = reactive({
  deliveryNo: [{ required: true, message: "请输入物流单号", trigger: "blur" }],
});

onMounted(() => {
  handleQuery();
});
</script>
